﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using Sonce.Common;
using Sonce.Controls;
using Sonce.Editor;
using Sonce.Editor.Data;
using TreeViewItem = Microsoft.Windows.Controls.TreeViewItem;

namespace Sonce.Core
{
	public partial class Page : UserControl
	{
		#region Constructor
		/// <summary>
		/// Initializes a new Page instance.
		/// </summary>
		public Page()
		{
			InitializeComponent();
			InitializeCommon();

			App.Current.Host.Content.Resized += new EventHandler(Content_Resized);
			App.Current.Host.Content.FullScreenChanged += new EventHandler(Content_FullScreenChanged);

			Loader.LoadDatabase("Xml/Database.xml", Loader.Sources.Resources);
			Loader.LoadMenu(ref menu, "Xml/Menu.xml", Loader.Sources.Resources);
			Loader.LoadToolbar(ref toolbar, "Xml/Toolbar.xml", Loader.Sources.Resources);
			Loader.LoadLibrary(ref tree, "Xml/Library.xml", Loader.Sources.Resources);
			LoadingAnimation.SetAnimation(pnlPreview, true);

			//TODO: For Sonce, start with 1,1 (not zero-based)
			//Matrix<int> matrix = new Matrix<int>(100, false, true);
			//matrix[0][0] = 10;
			//matrix[2][3] = 20;
			//matrix[5][5] = 30;
			//Console.WriteLine(matrix[2][3].ToString());
			//Console.WriteLine(matrix.Dump());

			//Temporary
			dvViewer.DataContext = new EditorDataContext();
		}
		#endregion

		#region Menu
		protected void menu_ItemClick(object sender, MenuEventArgs e)
		{
			if (e != null && e.OriginalSource != null && e.OriginalSource is MenuItem)
			{
				MenuItem menuItem = e.OriginalSource as MenuItem;
				if (menuItem.Tag != null && menuItem.Tag is Sonce.Common.ICommand)
				{
					runCommand(menuItem.Tag as Sonce.Common.ICommand);
				}
			}
		}
		#endregion

		#region Toolbar
		protected void toolbar_ItemClick(object sender, ToolbarEventArgs e)
		{
			if (e != null && e.OriginalSource != null && e.OriginalSource is ToolbarButton)
			{
				ToolbarButton button = e.OriginalSource as ToolbarButton;
				if (button.Tag != null && button.Tag is Sonce.Common.ICommand)
				{
					runCommand(button.Tag as Sonce.Common.ICommand);
				}
			}
		}
		#endregion

		#region Tree
		protected void tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
		{
			if (e.NewValue != null && e.NewValue is TreeViewItem)
			{
				TreeViewItem node = e.NewValue as TreeViewItem;
				if (node.Tag != null)
				{
					if (node.Tag is ElementTag)
					{
						ElementTag tag = node.Tag as ElementTag;
						string xaml = Loader.GetResourceString(AssemblyNames.Resource, tag.Source);
						tag.Xaml = xaml;

						loadPreview(xaml);

						runCommand(Commands.ElementTool, tag); //editor.SelectedTool = new ElementTool(xaml);
					}
					else if (node.Tag is Sonce.Common.ICommand)
					{
						runCommand(node.Tag as Sonce.Common.ICommand);
					}
				}
			}
		}

		/// <summary>
		/// Load a xaml preview in the preview box.
		/// </summary>
		/// <param name="xaml"></param>
		private void loadPreview(string xaml)
		{
			try
			{
				Grid grid = new Grid();
				grid.VerticalAlignment = VerticalAlignment.Center;
				grid.HorizontalAlignment = HorizontalAlignment.Center;
				UIElement element = (UIElement)XamlReader.Load(xaml);
				grid.Children.Add(element);
				pnlPreview.Children.Clear();
				pnlPreview.Children.Add(grid);
			}
			catch (Exception ex)
			{
				Logger.Log(ex, LogLevels.Detailed);
			}
		}
		#endregion

		#region Resize
		private void Content_FullScreenChanged(object sender, EventArgs e)
		{
			//updateSize();
		}

		private void Content_Resized(object sender, EventArgs e)
		{
			//updateSize();
		}
		#endregion

		#region Events
		private void UserControl_KeyDown(object sender, KeyEventArgs e)
		{
			//Pass pressed key to the editor
			editor.KeyDown(sender, e);
		}

		//private void compileService_CompileCompleted(object sender, CompileServiceEventArgs e)
		//{
		//    try
		//    {
		//        //Open a page in the current tab/window in browser
		//        HtmlPage.Window.Navigate(new Uri(e.Result), "_self");
		//    }
		//    catch
		//    {
		//        //May throw security exception if e.Result cannot be retrieved
		//    }
		//}
		#endregion

		#region Debug events
		private void cmbExtraPanel_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (cmbExtraPanel != null)
			{
				switch (cmbExtraPanel.SelectedIndex)
				{
					case 0:
						rdExtra.Height = new GridLength(0, GridUnitType.Star);
						dvViewer.Visibility = Visibility.Collapsed;
						txtNotes.Visibility = Visibility.Collapsed;
						break;

					case 1:
						rdExtra.Height = new GridLength(1, GridUnitType.Star);
						dvViewer.Visibility = Visibility.Collapsed;
						txtNotes.Visibility = Visibility.Visible;
						break;

					case 2:
						rdExtra.Height = new GridLength(1, GridUnitType.Star);
						dvViewer.Visibility = Visibility.Visible;
						txtNotes.Visibility = Visibility.Collapsed;
						break;
				}
			}
		}

		private void btnExportXmlToNotes_Click(object sender, RoutedEventArgs e)
		{
			txtNotes.Text = EditorDocument.ExportCircuitXml();
			cmbExtraPanel.SelectedIndex = 1;
		}
		#endregion
	}
}
